package com.study.io.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

import com.study.io.util.HostInfo;

public class BIOEchoServer {

	public static void main(String[] args) throws Exception {

		ServerSocket serverSocket = new ServerSocket(HostInfo.PORT);

		new Thread(() -> {
			try {
				Socket socket = serverSocket.accept();

				new Thread(() -> {
					InputStream inputStream = null;
					OutputStream outputStream = null;
					PrintStream out = null;
					byte[] data = null;
					try {
						data = new byte[1024];
						inputStream = socket.getInputStream();
						outputStream = socket.getOutputStream();
						out = new PrintStream(outputStream) ;
					} catch (Exception e) {
						e.printStackTrace();
					}
					while (true) {
						Scanner scanner = new Scanner(inputStream);  //阻塞
						if(scanner.hasNext()){
							String val = scanner.next().trim() ; // 去掉多余的空格内容
		                    System.err.println("{服务器端}" + val);
		                    try {
								outputStream.write(new StringBuffer("[ECHO]" + new String(val) + "\n").toString().getBytes());
								outputStream.flush();
								if(val.equalsIgnoreCase("byebye")){
									break;
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							//out.println("[ECHO]" + val);
							
						}
//						int len;
//						// 3. 按字节流方式读取数据
//						try {
//							while ((len = inputStream.read(data)) != -1) {
//								outputStream.write(new StringBuffer("[ECHO]" + new String(data)).toString().getBytes());
//								outputStream.flush();
//								System.out.println(new String(data, 0, len));
//
//							}
//						} catch (IOException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
					}
				}).start();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}).start();

	}
}
